/**
 * @description: 权限管理
 * @author: lxz
 * @update: lxz(2021-01-18)
 */

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@utils/auth'
import store from '@/store'

NProgress.configure({ showSpinner: false })
export default function (router, whiteList = []) {
	router.beforeEach(async (to, from, next) => {
		NProgress.start()
		// 获取token
		const token = getToken()
		if (token) {
			if (!store.getters.token) {
				const res = store.dispatch('user/setJwtTokenAndInfo', token)
				if (res) {
					// 有token
					if (to.path === '/login') {
						// 是登录页
						// 跳转首页
						next({ path: '/' })
						NProgress.done()
					} else {
						next()
					}
				} else {
					next(`/login?redirect=${to.path}`)
				}
			} else {
				// 有token
				if (to.path === '/login') {
					// 是登录页
					// 跳转首页
					next({ path: '/' })
					NProgress.done()
				} else {
					next()
				}
			}
		} else {
			if (whiteList.indexOf(to.path) !== -1) {
				// in the free login whitelist, go directly
				next()
			} else {
				// other pages that do not have permission to access are redirected to the login page.
				next(`/login?redirect=${to.path}`)
				NProgress.done()
			}
		}
	})

	router.afterEach((to, from) => {
		NProgress.done()
		// document.title = to.meta.title || $config.title
	})
}
